#!/usr/bin/perl
# check_memcached.pl
# yinqinghong.cn 20150407

use strict;
use warnings;
use Cache::Memcached;

my @mds;

#open(my $netstat, 'netstat -lnetpA inet|');

#while (<$netstat>) {
#    if (/\s(\S*):(\d+).*memcache/) {
#        push @mds, "$1:$2";
#    }
#}

if (@ARGV != 1) {
    print "Useage: check_memcached.pl port\n";
    exit 1;
}

my $info = `netstat -lnetA inet|grep $ARGV[0]|awk '{print \$4}'`;
        push @mds, "$info";
#print "$info\n";

if (!$mds[0]) {
    print "Memcached is not listening on ipv4 at this server.\n";
    exit 1;
}

#print "$mds[0]\n";

my $memc = new Cache::Memcached;
$memc->set_servers(\@mds);
my $stats = $memc->stats();
#print Dumper($stats);

for my $host (keys %{$stats->{hosts}}) {
        $host =~ /:(\d+)/;
        my $port = $1;
#        open (my $z, ">/tmp/_zabbix_memcached_stat_$port");

        for my $key (keys %{$stats->{hosts}{$host}{misc}}) {
                #print $z "STAT $key $stats->{hosts}{$host}{misc}{$key}\n";
                print  "STAT $key $stats->{hosts}{$host}{misc}{$key}\n";
        }

#        close ($z);
}
